﻿using AutoScaleHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tool
{
    public partial class Main : Form
    {

        AutoScale autoScale = new AutoScale();
       
        private readonly System.IO.Ports.SerialPort serialPort = new System.IO.Ports.SerialPort();

        private bool _isLoaded = false;

        // 波特率数值范围
        private readonly List<string> baudList = new List<string>() {
           "600","1200", "2400", "4800", "9600","14400", "19200", "28800","38400", "43000", "57600",
           "76800","115200","128000","230400","256000","460800","921600","1382400","自定义"
        };
        // 停止位
        private readonly List<string> stopList = new List<string> { "1", "1.5", "2" };
        // 数据位
        private readonly List<string> dataList = new List<string> { "5", "6", "7", "8" };
        // 校验位
        private readonly List<string> checkList = new List<string>() { "NONE", "ODD", "EVEN", "MARK", "SPACE" };
        //数据显示
        private readonly List<string> showList = new List<string>() { "HEX", "ASCII" };


        public Main()
        {
            InitializeComponent();
            autoScale.SetContainer(this);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void FileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void NewToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void Main_Load(object sender, EventArgs e)
        {
            _isLoaded = true;
            InitPorts();
            InitCheck();
            InitBaud();
            InitStop();
            InitDataShow();
           
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (_isLoaded)
            {
                this.SuspendLayout();
                autoScale.UpdateControlsLayout();
                this.ResumeLayout();
            }
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //异步委托一个线程，不然接收数据时会出现数据线程错误
            this.Invoke((EventHandler)(delegate
            {
                var showText = this.comboBox5.Text;
                if (serialPort.IsOpen)
                {
                    try
                    {
                        byte[] receivedData = new byte[serialPort.BytesToRead];//创建接收数据数组
                        serialPort.Read(receivedData, 0, receivedData.Length);//读取数据
                        var content = string.Empty;
                        //显示形式
                        switch (showText)
                        {
                            case "HEX":
                                for (int i = 0; i < receivedData.Length; i++)
                                {
                                    //ToString("X2") 为C#中的字符串格式控制符
                                    //X为     十六进制
                                    //2为 每次都是两位数
                                    content += (receivedData[i].ToString("X2") + " ");
                                }
                                break;
                            case "ASCII":
                                content = Encoding.GetEncoding("GB2312").GetString(receivedData);//防止乱码
                                break;
                        }
                        //接收文本框
                        this.textBox1.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss:ffff")}：{content} \r\n");
                        serialPort.DiscardInBuffer();//丢弃缓存区数据
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error");
                    }
                }
                else
                {
                    MessageBox.Show("请打开串口", "Error");
                }
            }));
        }



        /**
         * 初始化串口
         */
        public void InitPorts()
        {
            this.comboBox1.Items.Clear();//清除原有串口
            var comPostList = System.IO.Ports.SerialPort.GetPortNames().ToList();//读取串口
            if (comPostList != null && comPostList.Any())
            {
                comPostList = comPostList.OrderBy(x => x).ToList();
                foreach (var item in comPostList)
                {
                    this.comboBox1.Items.Add(item);
                }
                this.comboBox1.Text = comPostList.FirstOrDefault();//默认选择第一个串口
                this.comboBox1.Enabled = true;//打开选择框
            }
            else
            {
                MessageBox.Show("本机未找到串口！！！", "Error");
            }
        }


        /**
         * 初始化波特率
         */
        public void InitBaud()
        {
            foreach (var item in baudList)
            {
                this.comboBox2.Items.Add(item);
            }
            this.comboBox2.SelectedItem = "600";
        }


        /**
          * 初始化校验位
          */
        public void InitCheck()
        {
            foreach (var item in checkList)
            {
                this.comboBox4.Items.Add(item);
            }
            this.comboBox4.SelectedItem = "NONE";
        }


        /**
         * 
         * 初始化停止位
         */
        public void InitStop()
        {
            foreach (var item in stopList)
            {
                this.comboBox3.Items.Add(item);
            }
            this.comboBox3.SelectedItem = "1";
        }

        /**
          * 
          * 初始化数据显示
        */
        public void InitDataShow()
        {
            foreach (var item in showList)
            {
                this.comboBox5.Items.Add(item);
            }
            this.comboBox5.SelectedItem = "ASCII";
        }


        /**
         * 设置串口 信息
         */
        private void SetSerialPort()
        {
            string strBuadRate = this.comboBox2.Text.Trim();
            //string strDataRate = this.cb_DataSelect.Text.Trim();
            string strCheckRate = this.comboBox4.Text.Trim();
            string strPortRate = this.comboBox1.Text.Trim();
            string strStopRate = this.comboBox3.Text.Trim();
            int IBaudBits = Convert.ToInt32(strBuadRate);
            //int IDataBits = Convert.ToInt32(strDataRate);
            serialPort.PortName = strPortRate;//设置串口号
            serialPort.BaudRate = IBaudBits;//设置波特率
            serialPort.DataBits = 8;//设置数据位
            serialPort.Encoding = Encoding.UTF8;
            //设置校验位
            switch (strCheckRate)
            {
                case "NONE":
                    serialPort.Parity = Parity.None;
                    break;
                case "ODD":
                    serialPort.Parity = Parity.Odd;
                    break;
                case "EVEN":
                    serialPort.Parity = Parity.Even;
                    break;
                case "MARK":
                    serialPort.Parity = Parity.Mark;
                    break;
                case "SPACE":
                    serialPort.Parity = Parity.Space;
                    break;
                default:
                    serialPort.Parity = Parity.None;
                    break;
            }
            //设置停止位
            switch (strStopRate)
            {
                case "1":
                    serialPort.StopBits = StopBits.One;
                    break;
                case "1.5":
                    serialPort.StopBits = StopBits.OnePointFive;
                    break;
                case "2":
                    serialPort.StopBits = StopBits.Two;
                    break;
                default:
                    serialPort.StopBits = StopBits.One;
                    break;
            }
            serialPort.ReadTimeout = 5000;//读取超时时间5s
        }


        /**
         * 打开串口
         */
        private void button1_Click(object sender, EventArgs e)
        {
            if (!serialPort.IsOpen)
            {
                try
                {
                    //设置串口
                    SetSerialPort();
                    //打开
                    serialPort.Open();
                    button1.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("打开串口失败：" + ex.Message);
                    button1.Enabled = true;
                }
                finally { 
                
                }
            }
            else {
                button1.Enabled = true;
                serialPort.Close();
            }

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void ReqPrtToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReqTool reqTool = new ReqTool();
            reqTool.Show();
            reqTool.Visible = false;
            reqTool.ShowDialog();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void ShowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Datax datax = new Datax();
            datax.Show();
            datax.Visible = false;
            datax.ShowDialog();
        }

        private void MonToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MonitorForm monitor = new MonitorForm();
            monitor.Show();
            monitor.Visible = false;
            monitor.ShowDialog();
        }


        private void Form1_FormClosed(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void ReadCardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ReadCard readCard = new ReadCard();
            readCard.Show();
            readCard.Visible = false;
            readCard.ShowDialog();
        }

        private void PcscToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Pcsc pcsc = new Pcsc();
            pcsc.Show();
            pcsc.Visible = false;
            pcsc.ShowDialog();
        }
    }
}
